import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { LikeVideo } from './likeVideo.entity';
import { RedisCacheService } from '../redisCache/redisCache.service';
import { Profit } from '../profit/profit.entity';
import DataBase from 'src/config/database';
import { profitEnum } from '../profit/profit.enum';
import { Video } from '../video/video.entity';
import { ProfitUnLockHome } from '../profitUnLockHome/profitUnLockHome.entity';
import { EnumProfitUnLockHome_Status } from '../profitUnLockHome/profitUnLockHome.enum';

@Injectable()
export class LikeVideoService {
  constructor(
    @InjectRepository(LikeVideo)
    private likeVideoRepository: Repository<LikeVideo>,
    private readonly redisCacheService: RedisCacheService,
    @InjectRepository(Profit)
    private profitRepository: Repository<Profit>,
    @InjectRepository(ProfitUnLockHome)
    private profitUnLockHomeRepository: Repository<ProfitUnLockHome>,
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
  ) {}

  findAll(): Promise<LikeVideo[]> {
    return this.likeVideoRepository.find();
  }

  findOne(id: number): Promise<LikeVideo> {
    return this.likeVideoRepository.findOne({where:{id}});
  }

  findOne_by_video_id(video_id: number, wx_user?: string): Promise<LikeVideo> {
    return this.likeVideoRepository.findOne({where:{video_id,wx_user}});
  }

  async remove(id: number): Promise<void> {
    await this.likeVideoRepository.delete(id);
  }

  async remove_by_video_id(video_id: number, wx_user: string): Promise<any> {
    let findWxLike = await this.likeVideoRepository.findOne({where:{video_id: video_id, wx_user: wx_user}})
   
    //查询是否有退款申请
    let findRefund = await this.profitRepository.query(`
      select profit.id from profit
      inner join answer on profit.answer_id = answer.id
      where profit.status = 3 and answer.video_id = ? and answer.check = 1 and profit.use_wx_user = ?
    `,[video_id, wx_user])

    let findRefundUnLockHome = await this.profitUnLockHomeRepository.query(`
      select profit_unlock_home.id from profit_unlock_home
      where profit_unlock_home.status = 3 and profit_unlock_home.video_id = ? and profit_unlock_home.use_wx_user = ?
    `,[video_id, wx_user])

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {

      if(findWxLike && findWxLike.share_wx_user){
        await this.likeVideoRepository.createQueryBuilder(null, queryRunner).update({delete_tag: 1}).where({id: findWxLike.id}).execute()
        // await this.likeVideoRepository.update({id:findWxLike.id}, {delete_tag: 1})
      }else{
        await this.likeVideoRepository.createQueryBuilder(null, queryRunner).delete().where({video_id: video_id, wx_user: wx_user}).execute()
        // await this.likeVideoRepository.delete({video_id, wx_user});
      }
      if(findRefund.length > 0){
        await this.profitRepository.createQueryBuilder(null, queryRunner).update({status: profitEnum.entry}).where({id: findRefund[0].id}).execute()
      }
      if(findRefundUnLockHome.length > 0){
        await this.profitUnLockHomeRepository.createQueryBuilder(null, queryRunner).update({status: EnumProfitUnLockHome_Status.entry}).where({id: findRefundUnLockHome[0].id}).execute()
      }
     
      await queryRunner.commitTransaction()
      await queryRunner.release();

      if(findWxLike){
        await this.redisCacheService.del(`videos:${findWxLike.video_id}:collection:${findWxLike.wx_user}`)
      }
      await this.redisCacheService.clear(`${wx_user}:consume_list:consume*`)
      await this.redisCacheService.del(`videos:${findWxLike.video_id}:profit:${findWxLike.wx_user}`)

    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }

    
  }

  async create(likeVideo: LikeVideo, shareuid: number): Promise<void> {
    let findVideo = await this.likeVideoRepository.query(`
      select video.*,
      (
        select v.id from video as v
        inner join platform on platform.ic_group = v.ic_group
        inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
        where v.id = video.id and v.check = 1 and v.source = 2 and v.ic_group is not null
          and v.id not in (
            select video.id from video
            where video.check = 1 and video.source = 2 and (
              video.ic_group in (
                select a.id from (
                  select distinct internet_celebrity_group.id from internet_celebrity_group 
                  left join platform on platform.ic_group = internet_celebrity_group.id
                  inner join video on video.ic_group = internet_celebrity_group.id
                  where (
                    (
                      internet_celebrity_group.type = 2 
                    )
                    or(
                      internet_celebrity_group.type = 0 and (
                        platform.platform in (select setting.value from setting where setting.key = 'level3')
                        or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                      )
                    )
                    or (
                      internet_celebrity_group.type = 3 
                    )
                  )
                ) a
              )
              or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
            )
          )
        limit 0,1
      ) as is_lib
      from video
      where video.id = ?
    `,[likeVideo.video_id])
    //查询是否有过收藏
    if(findVideo.length > 0 && findVideo[0].is_lib){
      //查询当前视频自己是否没有同提问，并且别人同提问且收到答案了
      let findQuestion = await this.likeVideoRepository.query(`
        select questions.id from questions where video_id = ? and wx_user = ?
      `, [likeVideo.video_id, likeVideo.wx_user])
      let findAnswer = await this.likeVideoRepository.query(`
        select questions.wx_user from questions 
        inner join wx_user on wx_user.openid = questions.wx_user
        where video_id = ? and rela_questions_wx_user is null and post_answer = 1 and wx_user.id = ?
      `, [likeVideo.video_id, shareuid])
      console.log(findQuestion, 'findAnswer', findAnswer)

      //查询是否回答并采纳或者删除采纳答案了
      let findAnswerAccept = await this.likeVideoRepository.query(`
        select answer.wx_user from answer
        inner join wx_user on wx_user.openid = answer.wx_user
        where answer.video_id = ? and wx_user.id = ? and (
          answer.check = 1 or (
            answer.check = 0 and answer.delete_tag = 1 and answer.ic_group is not null
          )
        )
      `,[likeVideo.video_id, shareuid])

      if(findQuestion.length === 0 && findAnswer.length > 0){
        likeVideo.share_wx_user = findAnswer[0].wx_user 
      }else if(findAnswerAccept.length > 0){
        likeVideo.share_wx_user = findAnswerAccept[0].wx_user 
      }else if(shareuid){
        let findUser = await this.likeVideoRepository.query(`select openid from wx_user where id = ?`,[shareuid])
        if(findUser.length > 0){
          likeVideo.share_wx_user = findUser[0].openid
        }
      }
    }else if(shareuid){
      let findUser = await this.likeVideoRepository.query(`select openid from wx_user where id = ?`,[shareuid])
      if(findUser.length > 0){
        likeVideo.share_wx_user = findUser[0].openid
      }
    }
    let findWxLike = await this.likeVideoRepository.findOne({where:{video_id: likeVideo.video_id, wx_user: likeVideo.wx_user, delete_tag: 1}})
    if(findWxLike){
      likeVideo.delete_tag = 0
      likeVideo.id = findWxLike.id
    }
    await this.likeVideoRepository.save(likeVideo);

    //清空收藏缓存
    await this.redisCacheService.del(`videos:${likeVideo.video_id}:collection:${likeVideo.wx_user}`)
    await this.redisCacheService.clear(`${likeVideo.wx_user}:consume_list:consume*`)
  }

  async update(likeVideo: LikeVideo): Promise<void> {
    await this.likeVideoRepository.save(likeVideo);
  }

  /**
   * 是否可以写答案
   */
  async isCreate(video_id: number){
    //视频是否存在
    let findVideo = await this.videoRepository.findOne({where:{id: video_id, check: 1, delete_tag: 0}})
    if(!findVideo){
      return {error: '视频不存在'}
    }
    return {}
  }
}
